import citycode from '@/assets/citycode.json';
import { nestedCityCode } from '@/components/CityCode/citycode';
import InputLnglat from '@/components/InputLnglat';
import RemoteSelect from '@/components/RemoteSelect';
import { getSchemeList } from '@/pages/Finance/Scheme/RuleList/service';
import { SUCCESS_CODE } from '@/utils/request';
import { ProFormRadio, ProFormText, StepsForm } from '@ant-design/pro-components';
import { Cascader, Form, Input, message, Modal } from 'antd';
import { TimePicker } from 'antd/es';
import moment from 'moment';
import { useState } from 'react';
import { judgeHas_exists, UpdateParkItem } from '../service';
import styles from '../style.less';
import type { ParkItem, updateParkItem } from '../types';

interface undateParkList {
  parkItemData: ParkItem;
  visible: boolean;
  unVisible: () => void;
  reloadFunc: () => void;
}

export default (props: undateParkList) => {
  const { visible, unVisible, parkItemData, reloadFunc } = props;
  const [parkName, setParkName] = useState<string>(parkItemData.name || '');
  const startTime = `${moment().format('YYYY-MM-DD')} ${parkItemData.open_time.split('-')[0]}:00`;
  const endTime = `${moment().format('YYYY-MM-DD')} ${parkItemData.open_time.split('-')[1]}:00`;
  const code = parkItemData?.city_code ? parkItemData?.city_code : 0;

  const getCity = () => {
    const district = citycode[code || ''];
    if (String(code).endsWith('0000')) {
      return `${district}`;
    } else if (!String(code).endsWith('0000') && String(code).endsWith('00')) {
      const province = citycode[parseInt(String(code / 10000)) * 10000];
      return `${province} / ${district}`;
    } else if (!String(code).endsWith('0000') && !String(code).endsWith('00')) {
      const province = citycode[parseInt(String(code / 10000)) * 10000];
      const city1 = citycode[parseInt(String(code / 100)) * 100];
      return `${province} / ${city1} / ${district}`;
    }
    return '无数据';
  };

  return (
    <div>
      <Modal
        onCancel={unVisible}
        centered
        visible={visible}
        title="更新停车场"
        width={800}
        footer={null}
      >
        <StepsForm<updateParkItem>
          onFinish={async (values) => {
            const schemeId = parkItemData.id;
            const value = {
              ...values,
            };
            const hide = message.loading('正在提交');
            try {
              const res = await UpdateParkItem(schemeId, value);
              hide();
              if (res.code === SUCCESS_CODE) {
                message.success('更新成功');
                unVisible();
                reloadFunc();
                return true;
              }
              message.error(`更新失败！${res.message}`);
              return false;
            } catch (error) {
              hide();
              message.error('更新失败！未知的错误！');
              return false;
            }
          }}
        >
          <StepsForm.StepForm
            title="车场信息"
            style={{ height: 270, width: 500 }}
            className={styles.stepsaction}
            onFinish={async () => {
              const res = await judgeHas_exists(parkName, parkItemData.id);
              if (res.data && parkName != parkItemData.name) {
                message.error(res.message);
                return false;
              } else {
                return true;
              }
            }}
          >
            <ProFormRadio.Group
              radioType="radio"
              name="type"
              label="车场类型"
              options={[
                {
                  label: '扫码停车',
                  value: 1,
                },
                {
                  label: '预约停车',
                  value: 2,
                },
                {
                  label: '普通停车不可预约',
                  value: 3,
                },
                {
                  label: '普通停车可预约',
                  value: 4,
                },
              ]}
              rules={[{ required: true, message: '请选择车场类型' }]}
              initialValue={parkItemData.type}
            />
            <Form.Item
              name="name"
              label="停车场名称"
              rules={[{ required: true, message: '请输入车场名称' }]}
              initialValue={parkItemData.name}
            >
              <Input
                placeholder="请输入"
                value={parkName}
                style={{ width: 328 }}
                onChange={(e) => {
                  setParkName(e.target.value);
                }}
              />
            </Form.Item>
            <Form.Item
              name="open_time"
              label="运营时间"
              rules={[{ required: true, message: '请选择运营时间' }]}
              initialValue={[moment(startTime), moment(endTime)]}
            >
              <TimePicker.RangePicker
                allowClear
                format={'HH:mm'}
                minuteStep={10}
                style={{ width: 328 }}
              />
            </Form.Item>
          </StepsForm.StepForm>
          <StepsForm.StepForm title="车场位置" className={styles.secondStep}>
            <Form.Item
              name="district"
              label="行政区"
              rules={[{ required: true, message: '请选择行政区' }]}
              style={{ width: 500 }}
              initialValue={getCity()}
            >
              <Cascader
                placeholder="选择所在地区"
                fieldNames={{ label: 'name', value: 'code', children: 'children' }}
                options={nestedCityCode}
              />
            </Form.Item>
            <ProFormText
              width={500}
              name="address"
              label="停车场详细位置"
              placeholder="请输入"
              rules={[{ required: true, message: '请输入停车场详细位置' }]}
              initialValue={parkItemData.address}
            />
            <Form.Item
              name="location"
              label="停车场经纬度"
              style={{ width: 500 }}
              rules={[{ required: true, message: '请在地图中选择停车场位置' }]}
              initialValue={{ lat: parkItemData.lat, lng: parkItemData.lng }}
            >
              <InputLnglat />
            </Form.Item>
          </StepsForm.StepForm>
          <StepsForm.StepForm title="计费规则">
            <ProFormRadio.Group
              radioType="radio"
              name="chargeRangeType"
              label="是否含有道闸"
              options={[
                {
                  label: '有道闸',
                  value: 1,
                },
                {
                  label: '无道闸',
                  value: 2,
                },
              ]}
              rules={[{ required: true, message: '请选择是否有道闸' }]}
              initialValue={parkItemData.charge_range_type}
            />
            <Form.Item
              name="scheme"
              label="停车计费规则"
              rules={[{ required: true, message: '必选' }]}
              initialValue={parkItemData.scheme}
            >
              <RemoteSelect
                style={{ width: '100%' }}
                fieldNames={{ key: 'id', value: 'id', label: 'name' }}
                request={async (name) => {
                  return await getSchemeList({ type: 1, name });
                }}
              />
            </Form.Item>
          </StepsForm.StepForm>
        </StepsForm>
      </Modal>
    </div>
  );
};
